package com.kaiyidiannao.activity.user_detail;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.alipay.android.app.sdk.AliPay;
import com.com.alipay.android.msp.demo.Keys;
import com.com.alipay.android.msp.demo.Result;
import com.com.alipay.android.msp.demo.Rsa;
import com.kaiyidiannao.activity.daydaycoupon.DdcDetailActivity;
import com.kaiyidiannao.activity.daydaycoupon.DdcShoppingSucessActivity;
import com.kaiyidiannao.adapter.OrderSHopAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.UIUitls;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.Order;
import com.kaiyidiannao.model.bean.OrderBean;
import com.kaiyidiannao.model.req.model.GetMyOrderDetail;
import com.kaiyidiannao.view.ActionBarView;
import com.taplinker.core.util.LogUtil;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by mark on 2014/7/10.
 */
public class OrderDetail extends BaseActionBarActivity implements Observer {

    private TextView orderStatus,orderNum,orderMoney,totalMoney,yunMoney,payWay,trueName,phone,addr;
    private String orderstatus,ordernum,ordermoney,totalmoney,yunmoney,payway,truename,mobile,address;
    private ActionBarView actionBarView;
    private Button payAgain;
    private LinearLayout pay;
    private ListView orderListView;
    private OrderSHopAdapter orderSHopAdapter;
    private ArrayList<OrderBean> orderBeans = DataCenter.orderBeans;
    private String userid;
    // 支付宝用
    public static final String TAG = "alipay-sdk";
    private static final int RQF_PAY = 1;
    private String subject = "耐克9022010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红";
    private String body = "2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红";
    private String total_fee = 0.00 + ""; //总价格
    private String payMethod;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_detail);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        Intent intent = getIntent();

        Order order = (Order) intent.getSerializableExtra("bean");
        userid = order.getBuyerid();
        orderstatus = order.getStatus();
        ordernum = order.getOrderid();
        totalmoney = order.getAmount();
        yunmoney = order.getFare();
        ordermoney = Float.parseFloat(totalmoney)+ Float.parseFloat(yunmoney)+"";
        truename = order.getBuyer_name();
        mobile = order.getBuyer_mobile();
        address = order.getBuyer_address();
        payway = order.getPayment();

        findId();
        showProgressDialog("正在加载");
        new GetMyOrderDetail(userid,ordernum).execute();
        showList();
    }

    public void findId(){
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        orderStatus = (TextView)findViewById(R.id.orderStatus);
        orderNum = (TextView)findViewById(R.id.orderNum);
        orderMoney = (TextView)findViewById(R.id.orderMoney);
        totalMoney = (TextView)findViewById(R.id.totalMoney);
        yunMoney = (TextView)findViewById(R.id.yunMoney);
        payWay = (TextView)findViewById(R.id.payWay);
        trueName = (TextView)findViewById(R.id.orderName);
        phone = (TextView)findViewById(R.id.orderMobile);
        addr = (TextView)findViewById(R.id.orderAddress);
        payAgain = (Button)findViewById(R.id.payAgain);
        pay = (LinearLayout)findViewById(R.id.pay);
        orderListView = (ListView)findViewById(R.id.orderListView);

        if(orderstatus.equals("0")){
            orderStatus.setText("等待付款");
            orderStatus.setTextColor(Color.RED);
        }else if(orderstatus.equals("1")){
            orderStatus.setTextColor(Color.RED);
            orderStatus.setText("等待发货");
        }else if(orderstatus.equals("2")){
            orderStatus.setTextColor(Color.GREEN);
            orderStatus.setText("交易成功");
        }

        orderNum.setText(ordernum);
        orderMoney.setText(ordermoney);
        totalMoney.setText(totalmoney);
        yunMoney.setText(yunmoney);
        trueName.setText(truename);
        phone.setText(mobile);
        addr.setText(address);
        payWay.setText(payway);

        actionBarView.title.setText("订单详情");

    }

    public void showList(){

        orderSHopAdapter = new OrderSHopAdapter(this,orderBeans);
        orderListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(OrderDetail.this, DdcDetailActivity.class);
                intent.putExtra("itemid",orderBeans.get(position).getItemid());
                startActivity(intent);
            }
        });
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        closeProgressDialog();

        if (flag == DataCenter.flag.GET_ORDER_DETAIL_SUCCESS
                || flag == DataCenter.flag.GET_ORDER_DETAIL_FAILED) { //类表数据

            String code = DataCenter.code;
            Log.d("code",code);
            if (flag == DataCenter.flag.GET_ORDER_DETAIL_SUCCESS) {
                if (code.equals(DataCenter.successFlag)) {
                    closeProgressDialog();
                    android.util.Log.d("orderBeans", orderBeans.size() + "-----------");
                    orderListView.setAdapter(orderSHopAdapter);
                    orderSHopAdapter.notifyDataSetChanged();
                    UIUitls.setListViewHeightBasedOnChildren(orderListView,2);
                    if (orderstatus.equals("0") && payway.equals("支付宝在线支付")){
                        pay.setVisibility(View.VISIBLE);
                        payAgain.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String title = "";
                                for (int i = 0;i<orderBeans.size();i++){
                                    title += orderBeans.get(i).getTitle();
                                }
                                subject = title;//商品名称
                                body = title;//商品详情介绍
                                DataCenter.orderid = ordernum;//订单号
                                total_fee = ordermoney;//支付金额
                                payMethod = payway;
                                initAlipayMethod();//开始支付
                            }
                        });
                    }
                } else {
                    closeProgressDialog();
                    return;
                }
            }

            if (flag == DataCenter.flag.GET_ORDER_DETAIL_FAILED) {
                closeProgressDialog();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, OrderDetail.class.getSimpleName() + ".onDestroy");
        DataCenter.orderBeans.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }


    //-------------------------------------------支付宝start----------------------------------------------------------

    /**
     * 支付宝支付方式
     */
    private void initAlipayMethod() {
        try {
            String info = getNewOrderInfo(0);
            String sign = Rsa.sign(info, Keys.PRIVATE);
            sign = URLEncoder.encode(sign);
            info += "&sign=\"" + sign + "\"&" + getSignType();
            // start the pay.
            Log.i(TAG, "info = " + info);

            final String orderInfo = info;
            new Thread() {
                public void run() {
                    AliPay alipay = new AliPay(OrderDetail.this, mHandler);

                    //设置为沙箱模式，不设置默认为线上环境
                    //alipay.setSandBox(true);

                    String result = alipay.pay(orderInfo);

                    Log.i(TAG, "Result---------------:" + result + "!");
                    Result rs = new Result(result);

                    Message msg = new Message();
                    msg.what = RQF_PAY;
                    msg.obj = rs.getResult();
                    msg.arg1 = rs.getResultCode();
                    Log.i(TAG, "result = " + msg.obj);
                    mHandler.sendMessage(msg);
                }
            }.start();

        } catch (Exception ex) {
            ex.printStackTrace();
            //showToast(R.string.remote_call_failed);
            showToast("Failure calling remote service");
        }
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String resultMSG = msg.obj.toString();//提示信息
            int code = msg.arg1; //状态码制


            Log.i(TAG, "mHandler = !" + resultMSG + "!");

            // 在这里进行回调处理
            switch (msg.what) {
                case RQF_PAY:
                    if (code == 9000) { //支付成功
                        paySucess();
                        showToast(resultMSG);
                    } else {
                        payFaild();
                        showToast(resultMSG, "支付失败");
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void payFaild() {
        // 1：关闭当前页面
        finish();
    }

    private void paySucess() {
        // 1：关闭当前页面
        finish();
        // 2：跳转到支付成功页面
        Intent intent = new Intent(OrderDetail.this, DdcShoppingSucessActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);

        bundle.putString("product_id", getOutTradeNo()); //订单号
        bundle.putString("alipay_method", payMethod + ""); //
        bundle.putString("price_count", total_fee + "");
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private String getNewOrderInfo(int position) {
        StringBuilder sb = new StringBuilder();
        sb.append("partner=\"");
        sb.append(Keys.DEFAULT_PARTNER);
        sb.append("\"&out_trade_no=\"");
        sb.append(getOutTradeNo());
        sb.append("\"&subject=\"");
        sb.append(subject);
        sb.append("\"&body=\"");
        sb.append(body);
        sb.append("\"&total_fee=\"");
        sb.append(total_fee + "");
        sb.append("\"&notify_url=\"");

        // 网址需要做URL编码
        sb.append(URLEncoder.encode("http://www.3tixa.com:8086/kaiyi/api/pay/alipay/notify.php"));
        sb.append("\"&service=\"mobile.securitypay.pay");
        sb.append("\"&_input_charset=\"UTF-8");
        sb.append("\"&return_url=\"");
        sb.append(URLEncoder.encode("http://m.alipay.com"));
        sb.append("\"&payment_type=\"1");
        sb.append("\"&seller_id=\"");
        sb.append(Keys.DEFAULT_SELLER);

        // 如果show_url值为空，可不传
        // sb.append("\"&show_url=\"");
        sb.append("\"&it_b_pay=\"1m");
        sb.append("\"");

        return new String(sb);
    }

    // 获取订单号码
    private String getOutTradeNo() {
//        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
//        Date date = new Date();
//        String key = format.format(date);
//
//        java.util.Random r = new java.util.Random();
//        key += r.nextInt();
//        key = key.substring(0, 15);
//        Log.d(TAG, "outTradeNo: " + key);

        String key = DataCenter.orderid;
        return key;
    }

    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    //-------------------------------------------支付宝end----------------------------------------------------------
}
